package com.xyz.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.dao.mapper.BusinessFileDaoMapper;
import com.xyz.dao.pojo.BusinessFileVo;
import com.xyz.dto.RepairEvaluateDto;
import com.xyz.dto.RepairWorkOrderDto;
import com.xyz.dto.WeChatPageAllDto;
import com.xyz.dto.enums.EnumBusinessType;
import com.xyz.dto.enums.EnumRepState;
import com.xyz.entity.mapper.BusinessFileMapper;
import com.xyz.entity.mapper.RepairEvaluateMapper;
import com.xyz.entity.mapper.RepairWorkOrderMapper;
import com.xyz.entity.mapper.SystemEmployeeMapper;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.RepairService;
import com.xyz.service.WeChatService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private RepairService repairService;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private BusinessFileMapper businessFileMapper;

    @Autowired
    private RepairEvaluateMapper repairEvaluateMapper;

    @Autowired
    private BusinessFileDaoMapper businessFileDao;

    /*
     * 首页-列表数量
     * */
    @Override
    public DataResult getHomeRepairCount(LoginInfo loginInfo) throws Exception {
        Map<String, Object> returnMap = new HashMap<>();
        //我发起的获取数据
        RepairWorkOrderExample myExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria myCriteria = myExample.createCriteria();
        myCriteria.andEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        long myCount = repairWorkOrderMapper.countByExample(myExample);
        returnMap.put("myCount",myCount);
        //待评价获取数据
        RepairWorkOrderExample edExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria edCriteria = edExample.createCriteria();
        //type = 1 我发起的；2待评价；3已评价
        edCriteria.andEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        edCriteria.andRepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
        edCriteria.andIsEvaluateEqualTo(0);
        long edCount = repairWorkOrderMapper.countByExample(edExample);
        returnMap.put("edCount",edCount);
        return DataResult.build9100(returnMap);
    }

    @Override
    public DataResult getRepairAll(LoginInfo loginInfo,WeChatPageAllDto weChatPageAllDto) throws Exception {
        Page<RepairWorkOrder> pageObject = PageHelper.startPage(NumberUtil.parseInt(weChatPageAllDto.getPageNum()), NumberUtil.parseInt(weChatPageAllDto.getPageSize()));
        //获取数据
        RepairWorkOrderExample tExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria repCriteria = tExample.createCriteria();
        //type = 1 我发起的；2待评价；3已评价
        repCriteria.andEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        if (weChatPageAllDto.getType().equals("1")) {

        } else if (weChatPageAllDto.getType().equals("2")) {
            repCriteria.andRepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            repCriteria.andIsEvaluateEqualTo(0);
        } else {
            repCriteria.andRepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            repCriteria.andIsEvaluateEqualTo(1);
        }

        if (StrUtil.isNotEmpty(weChatPageAllDto.getWorkOrderCode())) {
            repCriteria.andWorkOrderCodeLike("%" + weChatPageAllDto.getWorkOrderCode() + "%");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StrUtil.isNotEmpty(weChatPageAllDto.getStartTime())) {
            repCriteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(weChatPageAllDto.getStartTime()));
        }

        if (StrUtil.isNotEmpty(weChatPageAllDto.getEndTime())) {
            repCriteria.andCreateTimeLessThanOrEqualTo(sdf.parse(weChatPageAllDto.getEndTime()));
        }
        tExample.setOrderByClause("create_time desc");
        List<RepairWorkOrder> repairList = repairWorkOrderMapper.selectByExample(tExample);

        List<Map<String, Object>> list = new ArrayList<>();
        //故障类别
        Map<Integer, String> faultMap = commonService.getDictMap("TYPE_REP_FAULT");
        for (RepairWorkOrder rw : repairList) {
            Map<String, Object> map = new HashMap<>();
            map.put("repId", rw.getRepId());
            map.put("employeeName", commonService.getEmployeeNameById(rw.getEmployeeId()));
            map.put("workOrderCode", rw.getWorkOrderCode());
            map.put("emName", rw.getEmName());
            map.put("repDesc", rw.getRepDesc());
            map.put("emLocation", rw.getEmLocation());
            map.put("repState", rw.getRepState());
            map.put("repFaultTypeName",faultMap.getOrDefault(rw.getRepFaultType(),""));
            map.put("createTime", DateUtil.format(rw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(), list);
        return DataResult.build9100(gridData);
    }

    @Override
    public DataResult repairEvaluate(LoginInfo loginInfo,RepairEvaluateDto repairEvaluateDto) throws Exception {
        Long repId = Long.parseLong(repairEvaluateDto.getRepId());
        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repId);
        if(getRepairWorkOrder == null){
           return DataResult.build9250("维修工单查询不到");
        }
        RepairEvaluate repairEvaluate = new RepairEvaluate();
        repairEvaluate.setRepId(repId);
        repairEvaluate.setEmId(getRepairWorkOrder.getEmId());
        repairEvaluate.setEmName(getRepairWorkOrder.getEmName());
        repairEvaluate.setEmployeeId(loginInfo.getLoginEmployeeId());
        repairEvaluate.setUserRating(Integer.parseInt(repairEvaluateDto.getUserRating()));
        repairEvaluate.setEvaluateDesc(repairEvaluateDto.getEvaluateDesc());
        repairEvaluate.setCreateTime(new Date());
        repairEvaluateMapper.insert(repairEvaluate);

        RepairWorkOrder repairWorkOrder = new RepairWorkOrder();
        repairWorkOrder.setRepId(repId);
        repairWorkOrder.setIsEvaluate(1);
        repairWorkOrderMapper.updateByPrimaryKeySelective(repairWorkOrder);
        //图片
        String filePicCode = repairEvaluateDto.getFilePicCode();
        //视频
        String fileVideoCode = repairEvaluateDto.getFileVideoCode();
        if (StrUtil.isNotBlank(filePicCode)) {
            if (filePicCode.contains(",")) {
                String[] split = filePicCode.split(",");
                for (String spFilePicCode : split) {
                    insertWorkOrderFile(repairEvaluate.getRepId(), loginInfo.getLoginEmployeeId(), spFilePicCode, EnumBusinessType.EVALUATE.getBusType(), 1, 1);
                }
            } else {
                insertWorkOrderFile(repairEvaluate.getRepId(), loginInfo.getLoginEmployeeId(), filePicCode, EnumBusinessType.EVALUATE.getBusType(), 1, 1);

            }
        }
        if (StrUtil.isNotBlank(fileVideoCode)) {
            if (fileVideoCode.contains(",")) {
                String[] split = fileVideoCode.split(",");
                for (String spFileVideoCode : split) {
                    insertWorkOrderFile(repairEvaluate.getRepId(), loginInfo.getLoginEmployeeId(), spFileVideoCode, EnumBusinessType.EVALUATE.getBusType(), 1, 3);
                }
            } else {
                insertWorkOrderFile(repairEvaluate.getRepId(), loginInfo.getLoginEmployeeId(), fileVideoCode, EnumBusinessType.EVALUATE.getBusType(), 1, 3);
            }
        }
        return DataResult.build9100();
    }

    /*
    * 查询维修评价
    * */
    @Override
    public DataResult getRepairEvaluateAll(LoginInfo loginInfo, String pageNum, String pageSize) throws Exception {
        Page<RepairEvaluate> pageObject = PageHelper.startPage(NumberUtil.parseInt(pageNum), NumberUtil.parseInt(pageSize));
        RepairEvaluateExample example = new RepairEvaluateExample();
        example.createCriteria().andEmployeeIdEqualTo(loginInfo.getLoginEmployeeId());
        List<RepairEvaluate> repairEvaluates = repairEvaluateMapper.selectByExample(example);
        if(CollUtil.isEmpty(repairEvaluates)){
            GridData gridData = new GridData(pageObject.getTotal(), repairEvaluates);
            return DataResult.build9100(gridData);
        }
        //查询设备图片
        List<Long> emIds = repairEvaluates.stream().map(RepairEvaluate::getEmId).distinct().collect(Collectors.toList());
        List<BusinessFileVo> emFileList = businessFileDao.selectEmFileById(emIds);
        Map<Long, List<BusinessFileVo>> retainListMap = new HashMap<>();
        if(CollUtil.isNotEmpty(emFileList)){
            retainListMap = emFileList.stream().collect(Collectors.groupingBy(BusinessFileVo :: getBusTablesId));
        }
        //评价图片
        List<Long> ids = repairEvaluates.stream().map(RepairEvaluate::getId).collect(Collectors.toList());
        List<BusinessFileVo> evFileList = businessFileDao.selectBusinessFileListByCodes(ids, EnumBusinessType.EVALUATE.getBusType());
        //组装图片数据fileType 1图片，3视频，
        List<BusinessFileVo> picList = evFileList.stream().filter(t -> t.getFileType() == 1).collect(Collectors.toList());
        List<BusinessFileVo> videoList = evFileList.stream().filter(t -> t.getFileType() == 3).collect(Collectors.toList());
        Map<Long, List<BusinessFileVo>> picMap = getEvFileMap(picList);
        Map<Long, List<BusinessFileVo>> videoMap = getEvFileMap(videoList);

        List<Map<String, Object>> list = new ArrayList<>();
        for (RepairEvaluate re : repairEvaluates) {
            Map<String, Object> map = new HashMap<>();
            if(re.getEmId() == 0){
                map.put("emUrl", null);
            }else {
                List<BusinessFileVo> businessFileVos = retainListMap.get(re.getEmId());
                if(CollUtil.isNotEmpty(businessFileVos)){
                    map.put("emUrl", businessFileVos.get(0).getFileUrl());
                }else {
                    map.put("emUrl", null);
                }
            }
            map.put("emName", re.getEmName());
            map.put("employeeName", commonService.getEmployeeNameById(re.getEmployeeId()));
            map.put("userRating", re.getUserRating());
            map.put("evaluateDesc", re.getEvaluateDesc());
            map.put("picfileList", picMap.get(re.getId()));
            map.put("videofileList", videoMap.get(re.getId()));
            map.put("createTime", DateUtil.format(re.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
        }
        GridData gridData = new GridData(pageObject.getTotal(), list);
        return DataResult.build9100(gridData);
    }

    private Map<Long, List<BusinessFileVo>> getEvFileMap(List<BusinessFileVo> evFileList){
        if(CollUtil.isEmpty(evFileList)){
            return new HashMap<>();
        }
        return evFileList.stream().collect(Collectors.groupingBy(BusinessFileVo::getBusTablesId));
    }

    private SystemEmployee getEmployeeByPhoneNumber(String phoneNumber){
        SystemEmployeeExample example = new SystemEmployeeExample();
        example.createCriteria().andPhoneNumberEqualTo(phoneNumber);
        example.setOrderByClause("create_time desc limit 1");
        List<SystemEmployee> systemEmployees = systemEmployeeMapper.selectByExample(example);
        if(CollUtil.isNotEmpty(systemEmployees)){
            return systemEmployees.get(0);
        }
        return null;
    }

    private void insertWorkOrderFile(Long busTablesId, Long employeeId, String fileCode, int busType, int fileGroup, int fileType) {
        BusinessFile businessFile = new BusinessFile();
        businessFile.setBusTablesId(busTablesId);
        businessFile.setBusType(busType);
        businessFile.setFileGroup(fileGroup);
        businessFile.setEmployeeId(employeeId);
        businessFile.setFileCode(fileCode);
        businessFile.setFileType(fileType);
        businessFile.setCreateTime(new Date());
        businessFileMapper.insertSelective(businessFile);
    }

}
